import {Client} from '@stomp/stompjs'
import SockJS from 'sockjs-client'
import useUserStore from '@/store/modules/user'


// 连接配置
// const WEBSOCKET_ENDPOINT = 'http://localhost:8080/ws'
const WEBSOCKET_ENDPOINT = 'http://47.111.128.196:8080/prod-api/ws'
const RECONNECT_DELAY = 5000

export const stompClient = new Client({
    autoConnect: false,
    webSocketFactory: () => new SockJS(WEBSOCKET_ENDPOINT),
    connectHeaders: { 'X-Client-Type': 'web' },
    reconnectDelay: RECONNECT_DELAY,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,
    debug: (str) => console.debug('[STOMP]', str)
})

// 连接方法
export const connect = () => {
    return new Promise((resolve, reject) => {
        if (stompClient.active) {
            resolve(stompClient)
            return
        }

        stompClient.onConnect = (frame) => {
            console.log('STOMP 连接成功', frame)
            resolve(stompClient)
        }

        stompClient.onStompError = (frame) => {
            console.error('STOMP 协议错误:', frame.headers.message)
            reject(new Error(frame.headers.message))
        }

        stompClient.onWebSocketError = (event) => {
            console.error('WebSocket 错误:', event)
            reject(event)
        }

        stompClient.activate()
    })
}

// 断开连接
export const disconnect = () => {
    return new Promise((resolve) => {
        if (stompClient?.connected) {
            stompClient.deactivate()
            console.log('⏹️ 主动断开连接')
        }
        resolve()
    })
}

// 获取当前用户ID
export const getUserId = () => {
    const userStore = useUserStore()
    return Number(userStore.id)
}
